<?php

namespace App\Console\Commands\Guanyuan;

use App\Library\FeiShu\SendFs;
use App\Models\Common\ConfigModel;
use App\Remote\Feishu\FeishuMsgRemote;
use App\Remote\Guanyuan\GuanyuanRemote;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Blade;

class SourceDataParseCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'guanyuan:sourceDataParse';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '观远：数据分析';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        if (in_array(Carbon::now()->dayOfWeek, [6, 0])) {
            return 0;
        }

        $guanyuanConfig = ConfigModel::getSingleConfig("guanyuan", "sourceDataDetail", function ($value) {
            return jsonToArr($value, null);
        });

        collect($guanyuanConfig)->each(function ($config) {
            $sourceData = GuanyuanRemote::sourceData(
                $config["source"],
                $config["token"]
            );


            $renderData = collect($sourceData["data"] ?? [])->map(function ($single) {
                return [
                    "name"   => $single[0],
                    "source" => $single[1],
                    "status" => $single[2]
                ];
            })->values()->groupBy("source")->map(function (Collection $groupSource, $name) {
                $shelvesNum  = $groupSource->where("status", "上架")->count();
                $shortageNum = $groupSource->where("status", "缺货")->count();
                $total       = $groupSource->count();
                return [
                    "name"              => $name,
                    "totalNum"          => $total,
                    "shelvesNum"        => $shelvesNum,
                    "shortageNum"       => $shortageNum,
                    "shelvesRate"       => number_format($shelvesNum / $total, 3) * 100,
                    "shortageRate"      => number_format($shortageNum / $total, 3) * 100,
                    "shortageNameGroup" => $groupSource->where("status", "缺货")->pluck("name")->implode("、")
                ];
            })->sortByDesc("shortageNum")->values()->toArray();


            $msgTemplateContents = view()->file(app_path(
                    "Remote/Feishu/FsTemplate/Guanyuan") . "/GuanyuanSourceDataParse.blade.php",
                [
                    "executeDate" => formatDateYmd(time()),
                    "sourceData"  => $renderData
                ]
            )->render();

            collect($config["fsRobotGroup"])->each(function ($fsRobot) use ($msgTemplateContents) {
                SendFs::newRobot()->coverConfig($fsRobot["url"], $fsRobot["secret"])
                      ->setCardMessageBody(json_decode($msgTemplateContents, true))->send();
            });
        });


        return 0;
    }
}
